package com.ys.peony.rolecontrol.presenter;

import android.content.Context;
import android.text.TextUtils;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.ys.peony.R;
import com.ys.peony.app.BaseApplication;
import com.ys.peony.base.BaseContract;
import com.ys.peony.base.BasePresenter;
import com.ys.peony.database.DataBaseUtil;
import com.ys.peony.rolecontrol.RoleControlContract;
import com.ys.peony.rolecontrol.entity.Component;
import com.ys.peony.rolecontrol.entity.Info;
import com.ys.peony.rolecontrol.entity.Layout;
import com.ys.peony.rolecontrol.entity.Widget;
import com.ys.peony.rolecontrol.model.RoleControlModel;
import com.ys.peony.utils.ImageLoadUtils;
import com.ys.peony.utils.LogUtil;
import com.ys.peony.utils.YsUtil;
import com.zhitongyun.publics.greendao.ComponentDao;
import com.zhitongyun.publics.greendao.LayoutDao;
import com.zhitongyun.publics.greendao.WidgetDao;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import org.xmlpull.v1.XmlPullParser;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 59153 on 2017/9/20.
 */

public class RoleControlPresenter extends BasePresenter<RoleControlModel, BaseContract.IBaseView> implements RoleControlContract.iRoleControlPresenter {
    private final static String INFO = "info";
    private final static String COMPONENTS = "components";
    private final static String LAYOUT = "layout";

    private final static String ID = "id";
    private final static String VERSION = "version";
    private final static String ROLES = "roles";
    private final static String NAME = "name";
    private final static String DESCRIPTION = "description";
    private final static String COMPONENTID = "componentId";
    private final static String ACTION = "action";
    private final static String BUTTON = "button";
    private final static String BANNER = "banner";
    private final static String INCLUDE = "include";
    private final static String MAINID = "mainId";
    private final static String BLOCK = "block";
    private final static String CONTAINS = "contains";
    private final static String RULE = "rule";
    private final static String COMPONENT = "component";

    private Context mContext;
    private ChildLayout mChildLayout;

    public RoleControlPresenter(Context context) {
        mContext = context;
        relateModel(new RoleControlModel());
    }

    /**
     * 描述：解析xml主页配置文件
     */

    @Override
    public void parseRoleConfig() {
        InputStream is = null;
        try {
            is = BaseApplication.getInstance().getAssets().open("test.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (is == null) {
            return;
        }
        XmlPullParser parser = Xml.newPullParser();
        ///初始化xmlPull解析器
        try {
            parser.setInput(is, "utf-8");
            //读取文件类型
            int type = parser.getEventType();
            Info info = null;
            List<Widget> widgets = null;
            List<Layout> layouts = null;
            List<Component> components = null;
            Component component;
            Widget widget;
            Layout layout = null;
            int blockId = -1;
            String rule = "";
            int depth2;
            while (type != XmlPullParser.END_DOCUMENT) {
                switch (type) {
                    case XmlPullParser.START_TAG:
                        switch (parser.getName()) {
                            case INFO:
                                info = new Info();
                                break;
                            case COMPONENTS:
                                components = new ArrayList<>();
                                break;
                            case LAYOUT:
                                widgets = new ArrayList<>();
                                layouts = new ArrayList<>();
                                break;
                            case INCLUDE:
                                layout = new Layout();
                                layout.setMainId(parser.getAttributeValue("", MAINID));
                                layout.setInfoid(parser.getAttributeValue("", MAINID));
                                layouts.add(layout);
                                break;
                            case BANNER:
                            case BUTTON:
                                component = new Component();
                                component.setId(parser.getAttributeValue("", ID));
                                component.setComponentId(parser.getAttributeValue("", COMPONENTID));
                                component.setAction(parser.getAttributeValue("", ACTION));
                                component.setName(parser.nextText());
                                component.setType(parser.getName());
                                components.add(component);
                                break;
                            case ID:
                                info.setId(parser.nextText());
                                break;
                            case VERSION:
                                info.setVersion(parser.nextText());
                                break;
                            case ROLES:
                                info.setRoles(parser.nextText());
                                break;
                            case NAME:
                                info.setName(parser.nextText());
                                break;
                            case DESCRIPTION:
                                info.setDescription(parser.nextText());
                                break;
                            case BLOCK:
                                ++blockId;
                                layout = new Layout();
                                layout.setBlockId(blockId);
                                layout.setInfoid(info.getId());
                                int depth = parser.getDepth();
                                while (true) {
                                    if (parser.next() == XmlPullParser.END_TAG) {
                                        if (BLOCK.equals(parser.getName())) {
                                            layouts.add(layout);
                                            break;
                                        }
                                    } else {
                                        if (CONTAINS.equals(parser.getName())) {
                                            rule = parser.getAttributeValue("", RULE);
                                            depth2 = parser.getDepth();
                                            while (true) {
                                                if (parser.next() == XmlPullParser.END_TAG) {
                                                    if (CONTAINS.equals(parser.getName())) {
                                                        break;
                                                    }
                                                } else {
                                                    if (CONTAINS.equals(parser.getName())) {
                                                        rule = parser.getAttributeValue("", RULE);
                                                        depth2 = parser.getDepth();
                                                    } else if (COMPONENT.equals(parser.getName())) {
                                                        widget = new Widget();
                                                        widget.setBlockId(blockId);
                                                        widget.setLevel(depth2 - depth);
                                                        widget.setRule(rule);
                                                        widget.setId(parser.getAttributeValue("", ID));
                                                        widgets.add(widget);
                                                    }
                                                }

                                            }
                                        }
                                    }
                                }
                                break;
                        }
                        break;
                }
                type = parser.next();
            }
            DataBaseUtil.getDaoSession().getInfoDao().insert(info);
            DataBaseUtil.getDaoSession().getLayoutDao().insertInTx(layouts);
            DataBaseUtil.getDaoSession().getComponentDao().insertInTx(components);
            DataBaseUtil.getDaoSession().getWidgetDao().insertInTx(widgets);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.e("DB", "error-->" + e.getMessage());
        }
    }

    /**
     * 描述：根据xml配置项动态绘制UI
     *
     * @return
     */
    public ViewGroup getUiLayout() {
        List<Info> infos = DataBaseUtil.getDaoSession().getInfoDao().loadAll();
        if (infos == null || infos.size() < 1) {
            return null;
        }
        Info info = infos.get(0);
        List<Layout> layouts = DataBaseUtil.getDaoSession().getLayoutDao()
                .queryBuilder().where(LayoutDao.Properties.Infoid.eq(info.getId())).list();
        LinearLayout root = new LinearLayout(mContext);
        root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        root.setOrientation(LinearLayout.VERTICAL);
        for (int i = 0; i < layouts.size(); i++) {
            LinearLayout layoutUI = new LinearLayout(mContext);
            layoutUI.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT));
            List<Widget> widgets = DataBaseUtil.getDaoSession().getWidgetDao().
                    queryBuilder().where(WidgetDao.Properties.BlockId.eq(layouts.get(i).getBlockId())).list();
            if (isVerticalBlockView(widgets.size(), widgets.get(0))) {
                layoutUI.setOrientation(LinearLayout.VERTICAL);
            } else {
                layoutUI.setOrientation(LinearLayout.HORIZONTAL);
            }
            mChildLayout = initChildLayout(widgets.size(), widgets.get(i));
            if (mChildLayout != null) {
                for (int j = 0; j < widgets.size(); j++) {
                    Widget widget = widgets.get(j);
                    Component component = DataBaseUtil.getDaoSession().getComponentDao().
                            queryBuilder().where(ComponentDao.Properties.Id.eq(widget.getId())).list().get(0);
                    if (component == null) {
                        continue;
                    }
                    if (widget.getLevel() <= 1) {
                        getChildView(component, widget, component.getType().trim());
                    }
                }
            }
            layoutUI = getBlockLayout(layoutUI);
            if (layoutUI.getChildCount() > 0) {
                root.addView(layoutUI);
                View view = new View(mContext);
                view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 200));
                root.addView(view);
            }
        }
        return root;
    }

    private LinearLayout getBlockLayout(LinearLayout blockLayout) {
        if (mChildLayout != null) {
            List<LinearLayout> layouts = mChildLayout.getLayouts();
            for (int i = 0; i < layouts.size(); i++) {
                blockLayout.addView(layouts.get(i));
            }
        }
        return blockLayout;
    }

    private MZBannerView initMZBanner(Widget widget) {
        int height = (YsUtil.getScreenHeight(mContext) - YsUtil.getStatusBarHeight(mContext)) / 4;
        MZBannerView banner = new MZBannerView(mContext, false);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, height);
        int w = YsUtil.getfenshu(widget.getRule())[0];
        params.weight = w;
        banner.setLayoutParams(params);
        return banner;
    }

    private MZBannerView getMZBanner(Component component, Widget widget) {
        final String url = "file:///android_asset/";
        String action = component.getAction().trim();
        if (!TextUtils.isEmpty(action)) {
            String[] urls = action.split(",");
            List<String> bannerImgs = new ArrayList<>();
            for (int i = 0; i < urls.length; i++) {
                bannerImgs.add(url + urls[i]);
            }
            if (bannerImgs.size() > 0) {
                MZBannerView banner = initMZBanner(widget);
                banner.setIndicatorVisible(true);
                banner.setPages(bannerImgs, new MZHolderCreator<BannerViewHolder>() {
                    @Override
                    public BannerViewHolder createViewHolder() {
                        return new BannerViewHolder();
                    }
                });
                banner.start();
                return banner;
            }

        }
        return null;
    }

    private void getChildView(Component component, Widget widget, String type) {
        View view = null;
        switch (type) {
            case BANNER:
                //view = getBannerView(component, widget);
                view = getMZBanner(component, widget);
                break;
            case BUTTON:
                view = getButtonViewBlock(component, widget);
                break;
        }
        LinearLayout layout = mChildLayout.getLayouts().get(mChildLayout.getIndex());
        if (view != null) {
            layout.addView(view);
        }
        int rule[] = YsUtil.getfenshu(widget.getRule());
        int count = mChildLayout.getCount();
        count += rule[0];
        if (count == rule[1]) {
            mChildLayout.setIndex(mChildLayout.getIndex() + 1);
            count = 0;
        }
        mChildLayout.setCount(count);
    }

    private Button getButtonViewBlock(Component component, Widget widget) {
        Button button = new Button(mContext);
        button.setText(component.getName());
        int rule[] = YsUtil.getfenshu(widget.getRule());
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.weight = rule[0];
        button.setLayoutParams(layoutParams);
        return button;
    }

    /**
     * 描述：判断当前板块view的布局方向
     *
     * @param size:该板块布局总widget个数
     * @param widget:参照控件
     * @return true：垂直布局，false：水平布局
     */

    private boolean isVerticalBlockView(int size, Widget widget) {
        Boolean result = false;
        if (widget == null || widget.getRule() == null) {
            return result;
        }
        String[] s = widget.getRule().split("/");
        if (s != null && s.length == 2) {
            int value = Integer.valueOf(s[1]);
            if (size > value) {
                result = true;
            }
        }
        return result;
    }

    /**
     * 描述：初始化block子布局
     *
     * @param size
     * @param widget
     * @return
     */
    private ChildLayout initChildLayout(int size, Widget widget) {
        int data[] = YsUtil.getfenshu(widget.getRule());
        if (data != null && data.length == 2) {
            int len = (int) ((Float.valueOf(size) / Float.valueOf(data[1]) * 1.00f) + 0.5);
            List<LinearLayout> layouts = new ArrayList<>();
            for (int i = 0; i < len; i++) {
                LinearLayout layout = new LinearLayout(mContext);
                layout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                layout.setOrientation(LinearLayout.HORIZONTAL);
                layouts.add(layout);
            }
            ChildLayout childLayout = new ChildLayout();
            if (layouts != null && layouts.size() > 0) {
                childLayout.setLayouts(layouts);
                childLayout.setIndex(0);
                childLayout.setCount(0);
            }
            return childLayout;
        }
        return null;
    }

    static class ChildLayout {
        private List<LinearLayout> layouts;
        private int index;
        private int count;

        public List<LinearLayout> getLayouts() {
            return layouts;
        }

        public void setLayouts(List<LinearLayout> layouts) {
            this.layouts = layouts;
        }

        public int getIndex() {
            return index;
        }

        public void setIndex(int index) {
            this.index = index;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }
    }

    public static class BannerViewHolder implements MZViewHolder<String> {
        private ImageView mImageView;

        @Override
        public View createView(Context context) {
            // 返回页面布局文件
            View view = LayoutInflater.from(context).inflate(R.layout.banner_item, null);
            mImageView = (ImageView) view.findViewById(R.id.banner_image);
            return view;
        }

        @Override
        public void onBind(Context context, int position, String data) {
            // 数据绑定
            ImageLoadUtils.showImg(mImageView, data);
        }
    }

}
